<template>
  <div>
    <!-- 搜索框 -->
    <form class="el-form el-form--inline" v-if="formDisplay">
      <div class="search-container">
        <!-- 岗位编码输入框 -->
        <div class="el-form-item el-form-item--medium">
          <label for="postCode" class="el-form-item__label">岗位编码</label>
          <div class="el-form-item__content">
            <el-input v-model="paginationQuery.code" placeholder="请输入用岗位编码"/>
          </div>
        </div>
        <!-- 岗位名称输入框 -->
        <div class="el-form-item el-form-item--medium">
          <label for="postName" class="el-form-item__label">岗位名称</label>
          <div class="el-form-item__content">
            <el-input v-model="paginationQuery.name" placeholder="请输入岗位名称"/>
          </div>
        </div>

        <div class="el-form-item el-form-item--medium">
          <label for="status" class="el-form-item__label">状态</label>
          <div class="el-form-item__content">
            <el-select v-model="paginationQuery.status" placeholder="岗位状态">
              <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="el-form-item el-form-item--medium">
          <div class="el-form-item__content">
            <el-button type="primary" icon="el-icon-search" @click="search(1)">搜索</el-button>
            <!-- 重置按钮 -->
            <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
          </div>
        </div>

      </div>
    </form>


    <!-- 操作按钮 -->
    <div class="button-container">
      <el-button type="primary" @click="add"><i class="el-icon-plus"></i>添加</el-button>
      <el-button type="success" :disabled="this.multipleSelection.length!==1" @click="modify"><i
          class="el-icon-edit"></i>修改
      </el-button>
      <el-button type="danger" :disabled="this.multipleSelection.length===0" @click="del"><i class="el-icon-delete"></i>删除
      </el-button>
      <el-button type="warning" @click="exportExcel"><i class="el-icon-download"></i>导出</el-button>
    </div>

    <!-- 隐藏按钮 -->
    <el-tooltip content="隐藏" placement="top">
      <el-button icon="el-icon-search" circle @click="hide" class="search-button"></el-button>
    </el-tooltip>

    <!-- 重置按钮 -->
    <el-tooltip content="重置" placement="top">
      <el-button icon="el-icon-refresh" circle @click="reset" class="search-button"></el-button>
    </el-tooltip>

    <el-table
        ref="multipleTable"
        :data="posts"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="80"
          align="center">
      </el-table-column>
      <el-table-column
          prop="postId"
          label="岗位编号"
          width="150"
          align="center">
      </el-table-column>

      <el-table-column
          prop="postCode"
          label="岗位编码"
          width="150"
          align="center">
      </el-table-column>


      <el-table-column
          prop="postName"
          label="岗位名称"
          width="150"
          align="center">
      </el-table-column>
      <el-table-column
          prop="postSort"
          label="岗位排序"
          width="150"
          align="center">
      </el-table-column>

      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <template v-if="scope.row.status === '0'">
            <span type="text">正常</span>
          </template>
          <template v-else>
            <span type="text">停用</span>
          </template>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="创建时间" width="150" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column
          label="操作"
          width="465"
          align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="modify1(scope.row)">
            <i class="el-icon-edit">修改</i>
          </el-button>
          <el-button type="text" @click="del1(scope.row.postId, scope.row.postId)">
            <i class="el-icon-delete">删除</i>
          </el-button>
        </template>
      </el-table-column>
    </el-table>


    <!--分页-->
    <div class="block">
      <!--分页-->
      <el-pagination
          background
          :total="total"
          @size-change="sizeTo" @current-change="interface"
          layout="total,sizes, prev, pager, next, jumper"
          :page-sizes="[1,10, 20, 30, 50]"
          style="float: right"/>
      <div style="clear: both"/><!--清除浮动-->
    </div>

    <!--新增修改弹窗-->
    <el-dialog :title="dialogTitle " :visible.sync="dialogFormVisibletianjia">
      <div>
        <el-row :gutter="15">
          <el-form :model="post" :rules="promptBox" ref="promptBox" size="medium" label-width="100px">
            <el-form-item label="岗位名称" prop="postName">
              <el-input v-model="post.postName" placeholder="请输入岗位名称" clearable :style="{width: '90%'}">
              </el-input>
            </el-form-item>
            <el-form-item label="岗位编码" prop="postCode">
              <el-input v-model="post.postCode" placeholder="请输入编码名称" clearable :style="{width: '90%'}">
              </el-input>
            </el-form-item>
            <el-form-item label="岗位顺序" prop="postSort">
              <el-input-number v-model="post.postSort" controls-position="right" :min="0" :max="10"></el-input-number>
            </el-form-item>
            <el-form-item label="岗位状态" prop="status">
              <el-radio v-model="post.status" label="0">正常</el-radio>
              <el-radio v-model="post.status" label="1">停用</el-radio>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="post.remark" placeholder="请输入内容"></el-input>
            </el-form-item>

            <el-form-item size="large">
              <el-button type="primary" @click="submitForm">提交</el-button>
              <el-button @click="cancel">取消</el-button>
            </el-form-item>
          </el-form>
        </el-row>
      </div>
    </el-dialog>

  </div>
</template>

<script>

export default {
  data() {
    return {
      dialogTitle: '',
      post: {
        'postId': null,
        'postCode': '',
        'postName': '',
        'postSort': '',
        'status': '',
        'createBy': '',
        'createTime': '',
        'updateBy': '',
        'updateTime': '',
        'remark': ''
      },
      // 分页+查询参数
      paginationQuery: {
        current: 1,
        size: 5,
        code: '',
        name: '',
        status: ''
      },
      multipleSelection: [],
      posts: [],
      // 显示、停用
      statusOptions: [
        {
          value: '0',
          label: '正常'
        },
        {
          value: '1',
          label: '停用'
        }],
      // 分页需要用到的参数
      pages: 1,
      total: 1,
      // 修改按钮非单个禁用(多选框)
      single: true,
      // 删除 非多个禁用
      multiple: true,
      formDisplay: true,
      dialogFormVisibletianjia: false,
      //弹出层输入框提示men
      promptBox: {
        postCode: [{required: true, message: '请输入岗位名称', trigger: 'blur'}],
        postName: [{
          required: true,
          message: '请输入编码名称',
          trigger: 'blur'
        }],
        postSort: [{
          required: true,
          message: '请输入岗位顺序',
          trigger: 'blur'
        }],
        remark: [{
          required: true,
          message: '请输入备注',
          trigger: 'blur'
        }],
      }
    }
  },
  methods: {
    //更改每页条数
    sizeTo(size) {
      this.paginationQuery.size = size;
      this.interface(1);
    },
    interface(current) {
      this.paginationQuery.current = current
      this.$axios.get('/sysPost/findPage', {params: this.paginationQuery})
          .then(result => {
            if (result.data.data) {
              this.posts = result.data.data.records
              this.pages = result.data.data.pages
              this.total = result.data.data.total
            }
          })
    },
    search(current) {
      this.paginationQuery.current = current
      // console.log('sdrzsrherdxxtjdr' + JSON.stringify(this.paginationQuery))
      this.$axios.get('/sysPost/findPage', {params: this.paginationQuery})
          .then(result => {
            if (result.data.data) {
              this.posts = result.data.data.records
              this.pages = result.data.data.pages
              this.total = result.data.data.total
            }
          })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
    // 折叠隐藏查询框
    hide() {
      this.formDisplay = !this.formDisplay
    },
    // 模糊查询重置
    reset() {
      this.paginationQuery = {}
      this.search(1)
    },
    //   新增
    add() {
      this.dialogTitle = '添加岗位';
      this.post = {
        'postId': null,
        'postCode': '',
        'postName': '',
        'postSort': '',
        'status': '0',
        'remark': ''
      }
      // 清除表单验证状态和样式
      this.$nextTick(() => {
        this.$refs.promptBox.clearValidate();
      });
      this.dialogFormVisibletianjia = true;
    },
    //   提交表单
    submitForm() {
      if (this.$refs.promptBox && this.$refs.promptBox.validate) {
        // 如果 promptBox 存在且需要验证，则执行验证
        this.$refs.promptBox.validate(valid => {
          if (valid) {
            // 验证通过，执行提交操作
            this.handleFormSubmission();
          }
        });
      } else {
        // 如果 promptBox 不存在或不需要验证，直接执行提交操作
        this.handleFormSubmission();
      }
    },
    handleFormSubmission() {
      if (this.post.postId == null) {
        // 新增
        this.$axios.post("/sysPost/addSysPost", this.post)
            .then(result => {
              if (result.data.data) {
                this.interface(this.paginationQuery.current)
              }
            })
      } else {
        // 修改
        this.$axios.put("/sysPost/updateSysPost", this.post)
            .then(result => {
              if (result.data.data) {
                this.interface(this.paginationQuery.current)
              }
            });
      }
      this.dialogFormVisibletianjia = false;
    },
    //   重置表单
    cancel() {
      this.$refs.promptBox.resetFields();
      this.dialogFormVisibletianjia = false;
    },
    // 修改回填参数
    modify() {
      // 清除表单验证状态和样式
      this.$nextTick(() => {
        this.$refs.promptBox.clearValidate();
      });
      if (this.multipleSelection.length === 1) {
        this.post = JSON.parse(JSON.stringify(this.multipleSelection[0]));
      }
      this.dialogTitle = '修改岗位'
      this.dialogFormVisibletianjia = true;
    },
    modify1(row) {
      // 清除表单验证状态和样式
      this.$nextTick(() => {
        this.$refs.promptBox.clearValidate();
      });
      this.post = JSON.parse(JSON.stringify(row));
      this.dialogTitle = '修改岗位'
      this.dialogFormVisibletianjia = true;
    },
    // 批量删除
    del() {
      const postIdList = this.multipleSelection.map(item => item.postId);
      if (postIdList.length > 0) {
        this.$confirm(`确定删除岗位编码为 ${postIdList} 的岗位吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 用户点击确定时的操作
          this.$axios.delete('/sysPost/delSysPost/' + postIdList.join(','))
              .then(result => {
                if (result.data.data) {
                  this.interface(this.paginationQuery.current);
                }
              })
        }).catch(() => {
        });
      } else {
        this.$message.warning('请选择要删除的岗位');
      }
    },
    // 单个删除
    del1(id, postId) {
      this.$confirm(`确定删除岗位编码为 ${postId} 的岗位吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击确定时的操作
        this.$axios.delete('/sysPost/delSysPost/' + id)
            .then(result => {
              if (result.data.data) {
                this.interface(this.paginationQuery.current)
              }
            })
      }).catch(() => {
      });
    },
    // 导出Excel
    exportExcel() {
      // 显示加载状态
      const loadingInstance = this.$loading({
        lock: true,
        text: '导出中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      this.$confirm(`是否确认导出所有岗位数据项?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击确定时的操作
        this.$axios.get('/sysPost/exportSysPost', {responseType: 'blob'})
            .then(result => {
              // 关闭加载状态
              loadingInstance.close();

              // 检查是否有返回数据
              if (result.data) {
                // 创建Blob对象
                const blob = new Blob([result.data]);

                // 创建下载链接
                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);

                // 设置下载文件的名称
                link.download = '岗位数据.xlsx';

                // 模拟点击下载
                link.click();
              } else {
                // 处理没有返回数据的情况
                this.$message.warning('导出失败：未收到文件数据');
              }
            })
            .catch(error => {
              // 关闭加载状态
              loadingInstance.close();

              // 处理错误
              console.error('导出失败', error);
              this.$message.error('导出失败：' + error.message);
            });
      }).catch(() => {
        // 用户点击取消时的操作
        // 关闭加载状态
        loadingInstance.close();
      });
    },
    //   时间解析器
    parseTime(time, pattern) {
      if (!time) return null
      const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
      const date = typeof time === 'object' ? time : new Date(time)
      const formatObj = {
        y: date.getFullYear(),
        m: (date.getMonth() + 1).toString().padStart(2, '0'),
        d: date.getDate().toString().padStart(2, '0'),
        h: date.getHours().toString().padStart(2, '0'),
        i: date.getMinutes().toString().padStart(2, '0'),
        s: date.getSeconds().toString().padStart(2, '0'),
        a: date.getDay()
      }
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        if (key === 'a') return ['日', '一', '二', '三', '四', '五', '六'][formatObj[key]]
        return formatObj[key] || 0
      })
      return time_str
    },
  },
  mounted() {
    this.interface(1)
  }

}
</script>

<style>
.search-container {
  display: flex;
  align-items: flex-end;
}

.el-form-item__label {
  width: 68px;
  margin-bottom: 0; /* 为了确保垂直对齐，将标签的下边距设置为0 */
}

.button-container {
  margin-top: 10px;
  display: flex;
  align-items: flex-end;
}

.search-button {
  margin-left: 10px;
}
</style>
